/**
 * Created by ss on 16/4/17.
 */
var HOST = 'localhost',
    USER = 'logitic',
    PASSWORD = 'suzhou360',
    DATABASE = 'logistic';
var mysql = require('mysql');
var Promise = require("bluebird");
module.exports = {
    db: null,
    init: function () {
        this.db = Promise.promisifyAll(mysql.createConnection({
            host: '127.0.0.1',
            user: 'logistic',
            password: 'suzhou360',
            database: 'logistic'
        }));
    },
    getSelectStr: function (tableName, object) {
        var result = "select * from " + tableName + " ";
        var whereStr = "";
        var valueArr = [];
        var andArr = [];
        if (object) {
            whereStr += "where ";
            for(var i in object) {
                andArr.push(i + "=?");
                valueArr.push(object[i]);
            }
        }
        return {
            str: result + whereStr + andArr.join(" and "),
            valueArr: valueArr
        }
    },
    getInsertStr: function (table, object) {
        var whereStr = "";
        var keyArr = [];
        var valueArr = [];
        var posiArr = [];
        if (!object) {
            return false;
        } else {
            for(var i in object) {
                keyArr.push(i);
                valueArr.push(object[i]);
                posiArr.push("?");
            }
        }
        return {
            str: "INSERT INTO " + table + " (" + keyArr.join(",") + ") VALUES (" + posiArr.join(",") + ")",
            valueArr: valueArr
        };
    },
    getUpdateStr: function (table, object, whereObject) {
        var keyArr = [];
        var valueArr = [];
        var posiArr = [];
        var whereStr = "";
        var whereArr = [];
        if (!object) {
            return false;
        } else {
            for(var i in object) {
                keyArr.push(i+"=?");
                valueArr.push(object[i]);
            }
        }
        if(whereObject) {
            whereStr += " where ";
            for(var i in whereObject) {
                whereArr.push(i+"=?");
                valueArr.push(whereObject[i]);
            }
            whereStr += whereArr.join(" and ");
        }
        return {
            str: "UPDATE " + table + " SET " + keyArr.join(",") + whereStr,
            valueArr: valueArr
        };
    }
};